import React, { useState, useEffect } from 'react';
import {
  Typography,
  Form,
  Input,
  Button,
  Switch,
  Select,
  Tabs,
  Card,
  Avatar,
  Upload,
  message,
  Divider,
  Space,
  Radio,
  Slider,
  Collapse,
  notification,
  Alert,
  Layout,
  Menu,
  Row,
  Col,
  TimePicker,
  InputNumber,
  Tooltip
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  SettingOutlined,
  CloudUploadOutlined,
  RobotOutlined,
  BellOutlined,
  GlobalOutlined,
  UploadOutlined,
  SaveOutlined,
  SafetyOutlined,
  DatabaseOutlined
} from '@ant-design/icons';
import { ShieldOutlined, Statistic } from '../components/icons/IconComponents';
import userService from '../api/userService';
import settingsService from '../api/settingsService';

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;
const { Panel } = Collapse;

const SettingsPage = () => {
  const [userForm] = Form.useForm();
  const [assistantForm] = Form.useForm();
  const [securityForm] = Form.useForm();
  const [notificationForm] = Form.useForm();
  
  const [userLoading, setUserLoading] = useState(false);
  const [assistantLoading, setAssistantLoading] = useState(false);
  const [securityLoading, setSecurityLoading] = useState(false);
  const [notificationLoading, setNotificationLoading] = useState(false);
  
  const [userData, setUserData] = useState(null);
  const [assistantSettings, setAssistantSettings] = useState(null);
  const [securitySettings, setSecuritySettings] = useState(null);
  const [notificationSettings, setNotificationSettings] = useState(null);

  // 获取用户信息
  useEffect(() => {
    const fetchUserData = async () => {
      setUserLoading(true);
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          const mockUserData = {
            username: '张铭',
            email: 'zhang.ming@example.com',
            phone: '13812345678',
            avatar: null,
            bio: '我是一名软件工程师，喜欢探索新技术。',
            language: 'zh_CN',
            country: 'CN',
            timezone: 'Asia/Shanghai'
          };
          setUserData(mockUserData);
          userForm.setFieldsValue(mockUserData);
          setUserLoading(false);
        }, 700);
        
        // 实际API调用示例：
        // const userData = await userService.getUserInfo();
        // setUserData(userData);
        // userForm.setFieldsValue(userData);
        // setUserLoading(false);
      } catch (error) {
        console.error('获取用户信息失败:', error);
        setUserLoading(false);
      }
    };

    fetchUserData();
  }, [userForm]);

  // 获取助手设置
  useEffect(() => {
    const fetchAssistantSettings = async () => {
      setAssistantLoading(true);
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          const mockAssistantSettings = {
            assistant_name: '智能助手',
            response_style: 'balanced',
            conversation_history: 30,
            auto_suggestions: true,
            pua_detection: true,
            tone_sensitivity: 'medium',
            emoji_usage: 'moderate',
            assistant_voice: 'female',
            conversation_analysis: true,
            language_model: 'gpt-4',
            custom_prompt: ''
          };
          setAssistantSettings(mockAssistantSettings);
          assistantForm.setFieldsValue(mockAssistantSettings);
          setAssistantLoading(false);
        }, 600);
        
        // 实际API调用示例：
        // const settings = await settingsService.getAssistantSettings();
        // setAssistantSettings(settings);
        // assistantForm.setFieldsValue(settings);
        // setAssistantLoading(false);
      } catch (error) {
        console.error('获取助手设置失败:', error);
        setAssistantLoading(false);
      }
    };

    fetchAssistantSettings();
  }, [assistantForm]);

  // 获取安全设置
  useEffect(() => {
    const fetchSecuritySettings = async () => {
      setSecurityLoading(true);
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          const mockSecuritySettings = {
            two_factor_auth: false,
            login_notification: true,
            auto_logout: 30,
            data_sharing: 'minimal',
            content_filtering: 'standard',
            api_access_enabled: false,
            conversation_encryption: true,
            last_password_change: '2025-03-15',
            privacy_mode: 'normal'
          };
          setSecuritySettings(mockSecuritySettings);
          securityForm.setFieldsValue(mockSecuritySettings);
          setSecurityLoading(false);
        }, 800);
        
        // 实际API调用示例：
        // const settings = await settingsService.getSecuritySettings();
        // setSecuritySettings(settings);
        // securityForm.setFieldsValue(settings);
        // setSecurityLoading(false);
      } catch (error) {
        console.error('获取安全设置失败:', error);
        setSecurityLoading(false);
      }
    };

    fetchSecuritySettings();
  }, [securityForm]);

  // 获取通知设置
  useEffect(() => {
    const fetchNotificationSettings = async () => {
      setNotificationLoading(true);
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          const mockNotificationSettings = {
            push_notifications: true,
            email_notifications: false,
            sound_enabled: true,
            message_preview: true,
            do_not_disturb: {
              enabled: false,
              start_time: '22:00',
              end_time: '08:00'
            },
            contact_requests: true,
            system_notifications: true,
            marketing_communications: false
          };
          setNotificationSettings(mockNotificationSettings);
          notificationForm.setFieldsValue(mockNotificationSettings);
          setNotificationLoading(false);
        }, 500);
        
        // 实际API调用示例：
        // const settings = await settingsService.getNotificationSettings();
        // setNotificationSettings(settings);
        // notificationForm.setFieldsValue(settings);
        // setNotificationLoading(false);
      } catch (error) {
        console.error('获取通知设置失败:', error);
        setNotificationLoading(false);
      }
    };

    fetchNotificationSettings();
  }, [notificationForm]);

  // 更新用户信息
  const handleUpdateUserInfo = async (values) => {
    setUserLoading(true);
    try {
      // 模拟API调用
      setTimeout(() => {
        setUserData({...userData, ...values});
        setUserLoading(false);
        message.success('个人信息更新成功');
      }, 800);
      
      // 实际API调用示例：
      // await userService.updateUserInfo(values);
      // setUserData({...userData, ...values});
      // setUserLoading(false);
      // message.success('个人信息更新成功');
    } catch (error) {
      console.error('更新用户信息失败:', error);
      setUserLoading(false);
      message.error('个人信息更新失败');
    }
  };

  // 更新助手设置
  const handleUpdateAssistantSettings = async (values) => {
    setAssistantLoading(true);
    try {
      // 模拟API调用
      setTimeout(() => {
        setAssistantSettings({...assistantSettings, ...values});
        setAssistantLoading(false);
        message.success('助手设置更新成功');
      }, 600);
      
      // 实际API调用示例：
      // await settingsService.updateAssistantSettings(values);
      // setAssistantSettings({...assistantSettings, ...values});
      // setAssistantLoading(false);
      // message.success('助手设置更新成功');
    } catch (error) {
      console.error('更新助手设置失败:', error);
      setAssistantLoading(false);
      message.error('助手设置更新失败');
    }
  };

  // 更新安全设置
  const handleUpdateSecuritySettings = async (values) => {
    setSecurityLoading(true);
    try {
      // 模拟API调用
      setTimeout(() => {
        setSecuritySettings({...securitySettings, ...values});
        setSecurityLoading(false);
        message.success('安全设置更新成功');
      }, 700);
      
      // 实际API调用示例：
      // await settingsService.updateSecuritySettings(values);
      // setSecuritySettings({...securitySettings, ...values});
      // setSecurityLoading(false);
      // message.success('安全设置更新成功');
    } catch (error) {
      console.error('更新安全设置失败:', error);
      setSecurityLoading(false);
      message.error('安全设置更新失败');
    }
  };

  // 更新通知设置
  const handleUpdateNotificationSettings = async (values) => {
    setNotificationLoading(true);
    try {
      // 模拟API调用
      setTimeout(() => {
        setNotificationSettings({...notificationSettings, ...values});
        setNotificationLoading(false);
        message.success('通知设置更新成功');
      }, 500);
      
      // 实际API调用示例：
      // await settingsService.updateNotificationSettings(values);
      // setNotificationSettings({...notificationSettings, ...values});
      // setNotificationLoading(false);
      // message.success('通知设置更新成功');
    } catch (error) {
      console.error('更新通知设置失败:', error);
      setNotificationLoading(false);
      message.error('通知设置更新失败');
    }
  };

  // 处理头像上传
  const handleAvatarUpload = info => {
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 上传成功`);
      // 实际应用中，这里应该更新用户的头像URL
      // setUserData({...userData, avatar: info.file.response.url});
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }
  };

  // 重置密码
  const handleResetPassword = () => {
    // 实际应用中，这里应该调用密码重置API
    notification.info({
      message: '密码重置链接已发送',
      description: '我们已向您的邮箱发送了一封含有密码重置链接的邮件，请查收。',
      duration: 5
    });
  };

  return (
    <div>
      <Title level={2}>个人设置</Title>
      <Paragraph>
        管理您的个人信息、助手偏好、安全设置和通知偏好。
      </Paragraph>
      
      <Tabs defaultActiveKey="1">
        <TabPane 
          tab={
            <span>
              <UserOutlined />
              个人信息
            </span>
          } 
          key="1"
        >
          <Card loading={userLoading}>
            {userData && (
              <Form
                form={userForm}
                layout="vertical"
                initialValues={userData}
                onFinish={handleUpdateUserInfo}
              >
                <div style={{ textAlign: 'center', marginBottom: 24 }}>
                  <Avatar 
                    size={100} 
                    icon={<UserOutlined />} 
                    src={userData.avatar}
                  />
                  <div style={{ marginTop: 16 }}>
                    <Upload 
                      name="avatar"
                      action="/api/upload"
                      showUploadList={false}
                      onChange={handleAvatarUpload}
                    >
                      <Button icon={<UploadOutlined />}>更换头像</Button>
                    </Upload>
                  </div>
                </div>
                
                <Form.Item
                  name="username"
                  label="用户名"
                  rules={[{ required: true, message: '请输入用户名' }]}
                >
                  <Input prefix={<UserOutlined />} />
                </Form.Item>
                
                <Form.Item
                  name="email"
                  label="电子邮箱"
                  rules={[
                    { required: true, message: '请输入电子邮箱' },
                    { type: 'email', message: '请输入有效的电子邮箱' }
                  ]}
                >
                  <Input />
                </Form.Item>
                
                <Form.Item
                  name="phone"
                  label="手机号码"
                >
                  <Input />
                </Form.Item>
                
                <Form.Item
                  name="bio"
                  label="个人简介"
                >
                  <Input.TextArea rows={4} />
                </Form.Item>
                
                <Divider>区域设置</Divider>
                
                <Form.Item
                  name="language"
                  label="界面语言"
                >
                  <Select>
                    <Option value="zh_CN">简体中文</Option>
                    <Option value="zh_TW">繁体中文</Option>
                    <Option value="en_US">English (US)</Option>
                    <Option value="ja_JP">日本語</Option>
                    <Option value="ko_KR">한국어</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item
                  name="timezone"
                  label="时区"
                >
                  <Select>
                    <Option value="Asia/Shanghai">中国标准时间 (GMT+8)</Option>
                    <Option value="America/New_York">美国东部时间 (GMT-5)</Option>
                    <Option value="Europe/London">伦敦时间 (GMT+0)</Option>
                    <Option value="Asia/Tokyo">东京时间 (GMT+9)</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={userLoading}
                    icon={<SaveOutlined />}
                  >
                    保存个人信息
                  </Button>
                </Form.Item>
              </Form>
            )}
          </Card>
        </TabPane>
        
        <TabPane 
          tab={
            <span>
              <RobotOutlined />
              助手设置
            </span>
          } 
          key="2"
        >
          <Card loading={assistantLoading}>
            {assistantSettings && (
              <Form
                form={assistantForm}
                layout="vertical"
                initialValues={assistantSettings}
                onFinish={handleUpdateAssistantSettings}
              >
                <Form.Item
                  name="assistant_name"
                  label="助手名称"
                >
                  <Input placeholder="为您的助手命名" />
                </Form.Item>
                
                <Form.Item
                  name="language_model"
                  label="语言模型"
                >
                  <Select>
                    <Option value="gpt-3.5">GPT-3.5 (更快，标准能力)</Option>
                    <Option value="gpt-4">GPT-4 (更智能，但较慢)</Option>
                    <Option value="claude">Claude (优秀的对话和推理能力)</Option>
                    <Option value="custom">自定义模型</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item
                  name="response_style"
                  label="回复风格"
                >
                  <Radio.Group>
                    <Radio.Button value="professional">专业正式</Radio.Button>
                    <Radio.Button value="friendly">友好亲切</Radio.Button>
                    <Radio.Button value="concise">简洁直接</Radio.Button>
                    <Radio.Button value="balanced">平衡</Radio.Button>
                  </Radio.Group>
                </Form.Item>
                
                <Form.Item
                  name="conversation_history"
                  label="对话历史保留天数"
                >
                  <Slider
                    min={7}
                    max={90}
                    marks={{
                      7: '7天',
                      30: '30天',
                      60: '60天',
                      90: '90天'
                    }}
                  />
                </Form.Item>
                
                <Divider>功能设置</Divider>
                
                <Form.Item
                  name="auto_suggestions"
                  label="智能回复建议"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="pua_detection"
                  label="PUA检测"
                  valuePropName="checked"
                  extra="自动检测并提示可能存在的PUA行为"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="conversation_analysis"
                  label="对话分析"
                  valuePropName="checked"
                  extra="提供对话风格和情感分析"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="emoji_usage"
                  label="表情符号使用"
                >
                  <Select>
                    <Option value="none">不使用</Option>
                    <Option value="minimal">最少</Option>
                    <Option value="moderate">适中</Option>
                    <Option value="abundant">丰富</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item
                  name="tone_sensitivity"
                  label="语气敏感度"
                >
                  <Select>
                    <Option value="low">低 (较少干预)</Option>
                    <Option value="medium">中 (平衡干预)</Option>
                    <Option value="high">高 (积极干预)</Option>
                  </Select>
                </Form.Item>
                
                <Collapse ghost style={{ marginBottom: 16 }}>
                  <Panel header="高级设置" key="1">
                    <Form.Item
                      name="custom_prompt"
                      label="自定义提示词"
                    >
                      <Input.TextArea 
                        rows={4} 
                        placeholder="输入自定义提示词，用于引导AI助手的行为..."
                      />
                    </Form.Item>
                    
                    <Form.Item
                      name="assistant_voice"
                      label="助手语音"
                    >
                      <Radio.Group>
                        <Radio value="male">男声</Radio>
                        <Radio value="female">女声</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Panel>
                </Collapse>
                
                <Form.Item>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={assistantLoading}
                    icon={<SaveOutlined />}
                  >
                    保存助手设置
                  </Button>
                </Form.Item>
              </Form>
            )}
          </Card>
        </TabPane>
        
        <TabPane 
          tab={
            <span>
              <ShieldOutlined />
              安全与隐私
            </span>
          } 
          key="3"
        >
          <Card loading={securityLoading}>
            {securitySettings && (
              <Form
                form={securityForm}
                layout="vertical"
                initialValues={securitySettings}
                onFinish={handleUpdateSecuritySettings}
              >
                <Alert
                  message="安全提示"
                  description="定期更改密码并启用双因素认证可以显著提高账户安全性。"
                  type="info"
                  showIcon
                  style={{ marginBottom: 16 }}
                />
                
                <Divider>账户安全</Divider>
                
                <div style={{ marginBottom: 16 }}>
                  <Text type="secondary">上次密码更改日期: {securitySettings.last_password_change}</Text>
                  <div style={{ marginTop: 8 }}>
                    <Button type="primary" onClick={handleResetPassword}>
                      更改密码
                    </Button>
                  </div>
                </div>
                
                <Form.Item
                  name="two_factor_auth"
                  label="双因素认证"
                  valuePropName="checked"
                  extra="登录时需要额外的验证码"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="login_notification"
                  label="登录通知"
                  valuePropName="checked"
                  extra="当账号在新设备登录时发送通知"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="auto_logout"
                  label="自动登出时间(分钟)"
                >
                  <Select>
                    <Option value={15}>15分钟</Option>
                    <Option value={30}>30分钟</Option>
                    <Option value={60}>1小时</Option>
                    <Option value={120}>2小时</Option>
                    <Option value={0}>从不</Option>
                  </Select>
                </Form.Item>
                
                <Divider>隐私设置</Divider>
                
                <Form.Item
                  name="privacy_mode"
                  label="隐私模式"
                >
                  <Radio.Group>
                    <Radio value="strict">严格 (最大化隐私保护)</Radio>
                    <Radio value="normal">标准 (平衡功能与隐私)</Radio>
                    <Radio value="minimal">最小 (优先功能体验)</Radio>
                  </Radio.Group>
                </Form.Item>
                
                <Form.Item
                  name="data_sharing"
                  label="数据共享"
                >
                  <Select>
                    <Option value="none">不共享任何数据</Option>
                    <Option value="minimal">最小化共享 (仅匿名使用数据)</Option>
                    <Option value="standard">标准共享 (匿名使用数据和交互改进)</Option>
                    <Option value="full">完全共享 (帮助改进所有服务)</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item
                  name="conversation_encryption"
                  label="对话加密"
                  valuePropName="checked"
                  extra="端到端加密所有聊天内容"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="content_filtering"
                  label="内容过滤"
                >
                  <Select>
                    <Option value="strict">严格</Option>
                    <Option value="standard">标准</Option>
                    <Option value="minimal">最小</Option>
                    <Option value="none">关闭</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item
                  name="api_access_enabled"
                  label="API访问"
                  valuePropName="checked"
                  extra="允许第三方应用通过API访问您的账户"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={securityLoading}
                    icon={<SaveOutlined />}
                  >
                    保存安全设置
                  </Button>
                </Form.Item>
              </Form>
            )}
          </Card>
        </TabPane>
        
        <TabPane 
          tab={
            <span>
              <BellOutlined />
              通知设置
            </span>
          } 
          key="4"
        >
          <Card loading={notificationLoading}>
            {notificationSettings && (
              <Form
                form={notificationForm}
                layout="vertical"
                initialValues={notificationSettings}
                onFinish={handleUpdateNotificationSettings}
              >
                <Form.Item
                  name="push_notifications"
                  label="推送通知"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="email_notifications"
                  label="邮件通知"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="sound_enabled"
                  label="通知声音"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="message_preview"
                  label="消息预览"
                  valuePropName="checked"
                  extra="在通知中显示消息内容预览"
                >
                  <Switch />
                </Form.Item>
                
                <Divider>免打扰设置</Divider>
                
                <Form.Item
                  name={['do_not_disturb', 'enabled']}
                  label="启用免打扰模式"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name={['do_not_disturb', 'start_time']}
                  label="开始时间"
                >
                  <Input type="time" />
                </Form.Item>
                
                <Form.Item
                  name={['do_not_disturb', 'end_time']}
                  label="结束时间"
                >
                  <Input type="time" />
                </Form.Item>
                
                <Divider>通知类型</Divider>
                
                <Form.Item
                  name="contact_requests"
                  label="联系人请求"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="system_notifications"
                  label="系统通知"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item
                  name="marketing_communications"
                  label="营销信息"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
                
                <Form.Item>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={notificationLoading}
                    icon={<SaveOutlined />}
                  >
                    保存通知设置
                  </Button>
                </Form.Item>
              </Form>
            )}
          </Card>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default SettingsPage; 